<?php
class AdminCmsCategoryForm extends DtCmsCategoryForm
{
	public function configure()
    {
		$this->setWidgets(array(
                'parent_id'	 	             	=> new sfWidgetFormChoice(array('choices' => $this->getCmsCategoryParent($this->getDefault("parent_id")))),
                'name'                			=> new sfWidgetFormInput(),
				'position'             			=> new sfWidgetFormInput()
				));
		$this->setValidators(array(
	            'name'			               	=>  new sfValidatorString(array('required' => "Tên chưa được nhập")),
				'positoin'						=>  new sfValidatorNumber(array('required' => "Thứ tự chưa được nhập")),
		));
        $this->widgetSchema->setNameFormat('cms_category[%s]');
		$this->widgetSchema->setLabels(array(
				'parent_id'						=> 'Mục cha',
				'name'							=> 'Tên',
				'position'						=> 'Thứ tự',
		));
	}
	
	private function getCmsCategoryParent($id)
	{
		$parents = array();
		$level = 0;
		$id += 0;

		$c = Doctrine_Query::create()
			->select('c.*')
			->from('DtCmsCategory c')
			->where('c.parent_id = ?', 0)
			->orderBy('c.position');
		
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			if ($result['id'] != $id) {
				$str = "";
				
				if ($level > 0)
				{
					for($i=0;$i<$level;$i++)
					{
						$str .= " ";
					}
					$str .= "- ";
				}
				$parents[$result['id']] = $str.$result['name'];
			
				$parents = array_merge($parents, $this->getTreeCmsCategory($result['id'], $level+2, $id));
			}
		}

		return array_merge(array(0=>'Không có mục cha'),$parents);
	}
	
	private function getTreeCmsCategory($parent_id, $level, $id)
	{
		$parents = array();
		$c = Doctrine_Query::create()
			->from('DtCmsCategory c')
			->where('c.parent_id = ?', $parent_id)
			->orderBy('c.position');
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			if ($result['id'] != $id)
			{
				$str = "";
				
				if ($level > 0)
				{
					for($i=0;$i<$level;$i++)
					{
						$str .= "&nbsp;&nbsp;";
					}
					$str .= "- ";
				}
				$parents[$result['id']] = $str.$result['name'];
				$parents = array_merge($parents, $this->getTreeCmsCategory($result['id'], $level+2, $id));
			}
		}
		return $parents;
	}
}
?>